#
# 此代码为自动化代码工具【JYGT-CODER】自动生成的文件，请勿手动编辑。              
#                                                               
# 作者: 修炼者 7457222@qq.com                                    
# 日期: 2024-12-16 23:03:18                                        
#
from sqlalchemy import create_engine,exc
from sqlalchemy.orm import sessionmaker
import time
 
from public.jygt_coder_common import getPTID

from public.jygt_coder_loger import get_logger 
logger = get_logger(__name__)

engine = create_engine("mysql+pymysql://root:root1234@127.0.0.1:3306/db_jygt", echo=True)
Session = sessionmaker(bind=engine)

connectionPool = {}

def checkValid(session):
  try:
    session.execute("SELECT 1")
    return True
  except Exception as exp:
    logger.error(exp)
    session.close()
    return False
  

def getMySQLSession(flag = True):
  if flag == False:
    if getPTID("MYSQL") in connectionPool:
      session = connectionPool[getPTID("MYSQL")] 
      session.close()
      del connectionPool[getPTID("MYSQL")] 
    
    return True
  
  if(getPTID("MYSQL") not in connectionPool) or(checkValid(connectionPool[getPTID("MYSQL")] ) is False):
    connectionPool[getPTID("MYSQL")] = Session()

  return connectionPool[getPTID("MYSQL")] 

def mydb_pool_session(func):
    def wrapper(self,*args, **kwargs):
        if hasattr(self,'session') == False :
          self.session = getMySQLSession(True)
          self.session_ref = 1
        else:
          self.session_ref+=1

        result = func(self, *args, **kwargs)

        self.session_ref-=1

        if self.session_ref <= 0:
          getMySQLSession(False)

        return result
    return wrapper

def mydb_transaction(func):
    def wrapper(self,*args, **kwargs):
        try:
            result = func(self, *args, **kwargs)
            if(result is None):
               return None
            self.session.commit()
            if isinstance(result, list) :
              for itm in result:
                self.session.refresh(itm)
            else:
               self.session.refresh(result)
        except Exception as exp:
            logger.info(exp)
            result = []    
            self.session.rollback()


        return result
    return wrapper


def mydb_copy(fromObj,toObj):
    for key in fromObj.__dict__:
        if key.startswith('_'):  # 忽略以 _ 开头的私有属性或特殊属性  
            continue  
        value = getattr(fromObj, key)  
        if value is not None:  
            setattr(toObj, key, value)  
